<template>
  <div class="app-main-content">
    <el-form
      ref="queryForm"
      v-loading="getTenantLoading"
      :inline="true"
      :model="queryForm"
      label-suffix=" :"
      @submit.native.prevent
    >
      <p>联合查询</p>
      <template v-for="item in tenants">
        <el-row :key="item.id">
          <el-col :span="3">
            <el-checkbox
              :value="isCheckedTenant(item.id)"
              :indeterminate="isIndeterminate(item.id)"
              @change="val => onTeantChange(item.id, val)"
            >{{ item.name }}</el-checkbox>
          </el-col>
          <el-col :span="21">
            <el-checkbox-group
              v-model="checkedAccountObjcts[item.id]"
              @change="val => onAccountChange(item.id, val)"
            >
              <el-checkbox
                v-for="account in item.accounts"
                :key="account.id"
                :label="account.id"
              >{{ account.name }}</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <div :key="'_'+ item.id" style="margin: 10px 0;" />
      </template>
    </el-form>
    <div style="margin: 20px 0;" />
    <p>
      <el-button type="primary" @click="onSearch('queryForm')">查询</el-button>
      <el-button @click="onResetForm('queryForm')">重置</el-button>
    </p>
    <p style="text-align: right;">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        :loading="delBtnLoading"
        :disabled="!selected.length"
        @click="handleDeleteAllItem"
      >删除</el-button>
    </p>
    <scmsa-table
      v-loading="tableLoading"
      class="margin-top-12"
      :data="tableData"
      :column="tableColumn"
      border
      :pagination="false"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalPage"
      @size-change="
        handlePageSizeChange({ v: arguments[0], refreshName: 'fetchAll' })
      "
      @pagination-current-change="
        handlePageCurrentChange({ v: arguments[0], refreshName: 'fetchAll' })
      "
      @selection-change="handleSelectionChange"
    />
    <el-drawer
      ref="drawer"
      :title="title"
      :visible.sync="dialog"
      direction="rtl"
      size="400px"
      :destroy-on-close="true"
      :modal-append-to-body="false"
      :wrapper-closable="false"
      @close="resetFieldsForm('actionForm')"
    >
      <div class="drawer__content">
        <scmsa-simple-form
          ref="actionForm"
          :model="actionForm"
          :rules="actionRules"
          label-suffix=" :"
          label-width="100px"
          :action-form-config="actionFormConfig"
        />
        <div class="drawer__footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="onSubmit('actionForm')"
          >{{ loading ? "提交中 ..." : "确定" }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import table from '@/mixins/table'
import form from '@/mixins/form'
import actionMixin from '@/mixins/actions-mixins'
import dialogMixin from '@/mixins/dialog-mixins'
import {
  get_official,
  save_official,
  remove_official,
  remove_official_all
} from '@/api/tenant-test'
import { get_tenants, get_current_tenant } from '@/api/tenant'

export default {
  name: 'TenantMutipleQuery',
  mixins: [table, form, actionMixin, dialogMixin],
  data() {
    return {
      removeRecord: remove_official,
      getTenantLoading: false,
      tenants: [],
      params: {
        page: 1,
        limit: 10
      },
      pageName: '公文',
      deleteRowInfo: {},
      tableData: [],
      checkedTenants: [],
      indeterminates: [],
      checkedAccountObjcts: {},
      actionRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        sender: [
          { required: true, message: '请输入发送人' }
        ],
        recipient: [
          { required: true, message: '请输入接收人' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    domain() {
      return [
        {
          type: 'selection',
          width: 55,
          align: 'center',
          formHide: true // 表单隐藏
        },
        {
          prop: 'title',
          label: '标题',
          dataType: 'string' // 数据类型
        },
        {
          prop: 'content',
          label: '内容',
          dataType: 'string',
          attrs: {
            // attrs form表单属性
            type: 'textarea'
          }
        },
        {
          prop: 'sender',
          label: '发送人',
          dataType: 'string'
        },
        {
          prop: 'recipient',
          label: '接收人',
          dataType: 'string'
        },
        {
          prop: 'created',
          label: '创建时间',
          dataType: 'string',
          formHide: true // 表单隐藏
        },
        {
          prop: 'type',
          label: '类型',
          dataType: 'string'
        },
        {
          label: '操作',
          width: 200,
          formHide: true,
          render: (h, params) => {
            return h('div', [
              // h(
              //   'el-button',
              //   {
              //     props: {
              //       type: 'text',
              //       size: 'small',
              //       icon: 'el-icon-edit',
              //       loading: this.initActionLoading(params, 'edit')
              //     },
              //     style: {
              //       marginRight: '5px'
              //     },
              //     on: {
              //       click: () => {
              //         this.handleEdit(params)
              //       }
              //     }
              //   },
              //   '编辑'
              // ),
              // h('el-divider', {
              //   props: {
              //     direction: 'vertical'
              //   }
              // }),
              h(
                'el-button',
                {
                  props: {
                    type: 'text',
                    size: 'small',
                    icon: 'el-icon-delete',
                    loading: this.initActionLoading(params, 'del')
                  },
                  on: {
                    click: () => {
                      this.handleDeleteItem(params)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ]
    }
  },
  mounted() {
    this.initTenant()
  },
  methods: {
    async initTenant() {
      this.getTenantLoading = true
      try {
        const [{ data }, { data: { accountId, tenantId }}] = await Promise.all([get_tenants(), get_current_tenant()])
        this.checkedAccountObjcts = data.reduce((pre, cur) => ({ ...pre, [cur.id]: cur.id === tenantId ? [accountId] : [] }), {})
        const temp = data.find(item => item.id === tenantId)
        const accounts = temp ? temp.accounts : []
        switch (accounts.length) {
          case 0:
            this.checkedTenants = []
            break
          case 1:
            this.checkedTenants = [tenantId]
            break
          default:
            this.indeterminates = [tenantId]
        }

        this.tenants = data
        this.fetchAll()
      } finally {
        this.getTenantLoading = false
      }
    },
    onResetForm() {
      this.initTenant()
    },
    // 获取列表的回调函数
    getAllCallback(res) {
      this.tableData = res.data || []
      this.totalPage = res.total
    },
    getAll() {
      const accountIds = Array.prototype.flat.call(Object.values(this.checkedAccountObjcts)).join(',')
      return get_official({ tenantIds: this.checkedTenants.join(','), accountIds })
    },
    createRecord(params) {
      return save_official(params)
    },
    getRecord(id) {
      return Promise.resolve({
        data: this.tableData.find(item => item.id === id)
      })
    }, // 获取详情api函数
    updateRecord() {}, // 编辑数据api函数
    handleDeleteItem(params) {
      this.removeRecord = remove_official
      this.handleDelete(params)
    },
    handleDeleteAllItem(params) {
      this.removeRecord = remove_official_all
      this.handleDeleteAll()
    },
    deleteBefore(data) {
      return data.split(',')
    },
    onTeantChange(id, val) {
      if (val) {
        this.setTenant(id, true)
        const accounts = this.tenants.find(item => item.id === id).accounts || []
        this.checkedAccountObjcts[id] = accounts.map(item => item.id)
      } else {
        this.setTenant(id, false)
        this.checkedAccountObjcts[id] = []
      }
      this.setIndeterminates(id, false)
    },
    onAccountChange(id, val) {
      const accounts = this.tenants.find(item => item.id === id).accounts || []
      const isAllChecked = val.length > 0 && val.length === accounts.length
      const isEmpty = val.length === 0

      if (isAllChecked) {
        this.setTenant(id, true)
        this.setIndeterminates(id, false)
      } else if (isEmpty) {
        this.setTenant(id, false)
        this.setIndeterminates(id, false)
      } else {
        this.setTenant(id, false)
        this.setIndeterminates(id, true)
      }
    },
    setTenant(id, val) {
      if (val) {
        if (!this.checkedTenants.some(item => item === id)) {
          this.checkedTenants = [id].concat(this.checkedTenants)
        }
      } else {
        this.checkedTenants = this.checkedTenants.filter(item => item !== id)
      }
    },
    setIndeterminates(id, val) {
      if (val) {
        if (!this.indeterminates.some(item => item === id)) {
          this.indeterminates = [id].concat(this.indeterminates)
        }
      } else {
        this.indeterminates = this.indeterminates.filter(item => item !== id)
      }
    },
    isCheckedTenant(id) {
      return this.checkedTenants.some(item => item === id)
    },
    isIndeterminate(id) {
      return this.indeterminates.some(item => item === id)
    }
  }
}
</script>

<style scoped></style>
